<?php
/**
 * CDK支付系统 - 安装脚本
 * 用于初始化数据库和创建管理员账户
 */

// 错误报告
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 检查是否已安装
if (file_exists('config/installed.lock')) {
    die('系统已安装，如需重新安装请删除 config/installed.lock 文件');
}

// 处理安装请求
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $dbHost = $_POST['db_host'] ?? 'localhost';
    $dbName = $_POST['db_name'] ?? 'cdkpay';
    $dbUser = $_POST['db_user'] ?? 'root';
    $dbPass = $_POST['db_pass'] ?? '';
    $adminUser = $_POST['admin_user'] ?? 'admin';
    $adminPass = $_POST['admin_pass'] ?? '';
    $adminEmail = $_POST['admin_email'] ?? 'admin@example.com';
    
    // 验证输入
    if (empty($dbHost) || empty($dbName) || empty($dbUser) || empty($adminUser) || empty($adminPass)) {
        $message = '请填写所有必填字段';
        $messageType = 'danger';
    } else {
        try {
            // 测试数据库连接
            $pdo = new PDO("mysql:host={$dbHost};charset=utf8mb4", $dbUser, $dbPass);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            // 创建数据库（如果不存在）
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            $pdo->exec("USE `{$dbName}`");
            
            // 创建表结构
            $sql = file_get_contents('database/schema.sql');
            if ($sql) {
                $pdo->exec($sql);
            } else {
                // 如果schema文件不存在，手动创建表
                createTables($pdo);
            }
            
            // 创建管理员账户
            $hashedPassword = password_hash($adminPass, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO admin_users (username, password, email, created_at) VALUES (?, ?, ?, NOW())");
            $stmt->execute([$adminUser, $hashedPassword, $adminEmail]);
            
            // 创建配置文件
            $configContent = generateConfig($dbHost, $dbName, $dbUser, $dbPass);
            if (!is_dir('config')) {
                mkdir('config', 0755, true);
            }
            file_put_contents('config/database.php', $configContent);
            
            // 创建安装锁定文件
            file_put_contents('config/installed.lock', date('Y-m-d H:i:s'));
            
            $message = '系统安装成功！请删除 install.php 文件以确保安全';
            $messageType = 'success';
            
        } catch (PDOException $e) {
            $message = '数据库连接失败: ' . $e->getMessage();
            $messageType = 'danger';
        } catch (Exception $e) {
            $message = '安装失败: ' . $e->getMessage();
            $messageType = 'danger';
        }
    }
}

/**
 * 手动创建数据库表
 */
function createTables($pdo) {
    // 管理员用户表
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS admin_users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            username VARCHAR(50) NOT NULL UNIQUE,
            password VARCHAR(255) NOT NULL,
            email VARCHAR(100),
            created_at DATETIME NOT NULL,
            updated_at DATETIME NOT NULL
        )
    ");
    
    // 商品表
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS products (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255) NOT NULL,
            description TEXT,
            price DECIMAL(10,2) NOT NULL,
            stock INT NOT NULL DEFAULT 0,
            status ENUM('active', 'inactive') DEFAULT 'active',
            sort_order INT DEFAULT 0,
            created_at DATETIME NOT NULL,
            updated_at DATETIME NOT NULL
        )
    ");
    
    // CDK码表
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS cdks (
            id INT AUTO_INCREMENT PRIMARY KEY,
            product_id INT NOT NULL,
            cdk_code VARCHAR(255) NOT NULL UNIQUE,
            status ENUM('available', 'used', 'expired') DEFAULT 'available',
            used_at DATETIME NULL,
            created_at DATETIME NOT NULL,
            FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
        )
    ");
    
    // 订单表
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS orders (
            id INT AUTO_INCREMENT PRIMARY KEY,
            order_no VARCHAR(50) NOT NULL UNIQUE,
            product_id INT NOT NULL,
            total_amount DECIMAL(10,2) NOT NULL,
            contact_info VARCHAR(255),
            status ENUM('pending', 'paid', 'completed', 'refunded', 'failed') DEFAULT 'pending',
            payment_method VARCHAR(50),
            payment_no VARCHAR(100),
            paid_at DATETIME NULL,
            cdk_code VARCHAR(255),
            created_at DATETIME NOT NULL,
            updated_at DATETIME NOT NULL,
            FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
        )
    ");
    
    // 支付日志表
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS payment_logs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            order_no VARCHAR(50) NOT NULL,
            payment_no VARCHAR(100),
            action ENUM('create', 'notify', 'return') NOT NULL,
            amount DECIMAL(10,2),
            params TEXT,
            created_at DATETIME NOT NULL
        )
    ");
    
    // 系统设置表
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS system_settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            setting_key VARCHAR(100) NOT NULL UNIQUE,
            setting_value TEXT,
            setting_type ENUM('string', 'integer', 'boolean', 'json') DEFAULT 'string',
            description VARCHAR(255),
            created_at DATETIME NOT NULL,
            updated_at DATETIME NOT NULL
        )
    ");
    
    // 插入默认设置
    $defaultSettings = [
        ['site_name', 'CDK支付系统', 'string', '网站名称'],
        ['site_url', 'http://localhost/cdkpay', 'string', '网站URL'],
        ['currency', 'CNY', 'string', '货币单位'],
        ['timezone', 'Asia/Shanghai', 'string', '时区'],
        ['easypay_pid', '1000', 'string', '易支付商户ID'],
        ['easypay_key', 'your_key_here', 'string', '易支付商户密钥'],
        ['easypay_api_url', 'https://zf.tuour.com/submit.php', 'string', '易支付API地址']
    ];
    
    $stmt = $pdo->prepare("INSERT INTO system_settings (setting_key, setting_value, setting_type, description, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())");
    foreach ($defaultSettings as $setting) {
        $stmt->execute($setting);
    }
}

/**
 * 生成数据库配置文件
 */
function generateConfig($host, $dbname, $username, $password) {
    return "<?php
/**
 * 数据库配置文件
 * 自动生成 - 请勿手动修改
 */
 
return [
    'host' => '{$host}',
    'dbname' => '{$dbname}',
    'username' => '{$username}',
    'password' => '{$password}',
    'charset' => 'utf8mb4'
];
?>";
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CDK支付系统 - 安装向导</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .install-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            max-width: 600px;
            width: 100%;
        }
        .install-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0;
            padding: 30px;
            text-align: center;
        }
        .install-body {
            padding: 30px;
        }
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
        }
        .step {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 10px;
            font-weight: bold;
            color: #6c757d;
        }
        .step.active {
            background: #667eea;
            color: white;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .requirements {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .requirement-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .requirement-item i {
            margin-right: 10px;
            width: 20px;
        }
        .requirement-item.valid {
            color: #28a745;
        }
        .requirement-item.invalid {
            color: #dc3545;
        }
    </style>
</head>
<body>
    <div class="install-container">
        <div class="install-header">
            <h1><i class="fas fa-shopping-cart me-2"></i>CDK支付系统</h1>
            <p class="mb-0">安装向导</p>
        </div>
        
        <div class="install-body">
            <?php if ($message): ?>
                <div class="alert alert-<?php echo $messageType === 'success' ? 'success' : 'danger'; ?>">
                    <?php echo $message; ?>
                    <?php if ($messageType === 'success'): ?>
                        <br><br>
                        <a href="admin/login.php" class="btn btn-success">进入后台管理</a>
                        <a href="index.php" class="btn btn-primary">访问前台页面</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            
            <?php if (!$message || $messageType !== 'success'): ?>
                <!-- 步骤指示器 -->
                <div class="step-indicator">
                    <div class="step active">1</div>
                    <div class="step">2</div>
                    <div class="step">3</div>
                </div>
                
                <!-- 系统要求检查 -->
                <div class="requirements">
                    <h5><i class="fas fa-check-circle me-2"></i>系统要求检查</h5>
                    <?php
                    $phpVersion = phpversion();
                    $pdoEnabled = extension_loaded('pdo_mysql');
                    $jsonEnabled = extension_loaded('json');
                    $curlEnabled = extension_loaded('curl');
                    $writeable = is_writable('.');
                    
                    $requirements = [
                        ['PHP版本 >= 7.4', version_compare($phpVersion, '7.4.0', '>='), $phpVersion],
                        ['PDO MySQL扩展', $pdoEnabled, $pdoEnabled ? '已启用' : '未启用'],
                        ['JSON扩展', $jsonEnabled, $jsonEnabled ? '已启用' : '未启用'],
                        ['cURL扩展', $curlEnabled, $curlEnabled ? '已启用' : '未启用'],
                        ['目录可写', $writeable, $writeable ? '可写' : '不可写']
                    ];
                    ?>
                    
                    <?php foreach ($requirements as $req): ?>
                        <div class="requirement-item <?php echo $req[1] ? 'valid' : 'invalid'; ?>">
                            <i class="fas fa-<?php echo $req[1] ? 'check' : 'times'; ?>"></i>
                            <?php echo $req[0]; ?>: <strong><?php echo $req[2]; ?></strong>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- 安装表单 -->
                <form method="POST">
                    <h5 class="mb-3"><i class="fas fa-database me-2"></i>数据库配置</h5>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">数据库主机</label>
                                <input type="text" class="form-control" name="db_host" value="localhost" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">数据库名称</label>
                                <input type="text" class="form-control" name="db_name" value="cdkpay" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">数据库用户名</label>
                                <input type="text" class="form-control" name="db_user" value="root" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">数据库密码</label>
                                <input type="password" class="form-control" name="db_pass">
                            </div>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <h5 class="mb-3"><i class="fas fa-user-shield me-2"></i>管理员账户</h5>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">管理员用户名</label>
                                <input type="text" class="form-control" name="admin_user" value="admin" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">管理员邮箱</label>
                                <input type="email" class="form-control" name="admin_email" value="admin@example.com" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">管理员密码</label>
                                <input type="password" class="form-control" name="admin_pass" required minlength="6">
                                <div class="form-text">密码长度至少6位</div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">确认密码</label>
                                <input type="password" class="form-control" name="admin_pass_confirm" required minlength="6">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="agreeTerms" required>
                            <label class="form-check-label" for="agreeTerms">
                                我同意安装CDK支付系统并理解相关风险
                            </label>
                        </div>
                    </div>
                    
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="fas fa-rocket me-2"></i>开始安装
                        </button>
                    </div>
                </form>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // 密码确认验证
        document.addEventListener('DOMContentLoaded', function() {
            const password = document.querySelector('input[name="admin_pass"]');
            const confirmPassword = document.querySelector('input[name="admin_pass_confirm"]');
            
            function validatePassword() {
                if (password.value !== confirmPassword.value) {
                    confirmPassword.setCustomValidity('密码不匹配');
                } else {
                    confirmPassword.setCustomValidity('');
                }
            }
            
            password.addEventListener('change', validatePassword);
            confirmPassword.addEventListener('keyup', validatePassword);
        });
    </script>
</body>
</html>
